package org.mspring.mlog.freemarker.directive;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.mspring.mlog.entity.Category;
import org.mspring.mlog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Gao Youbo
 * @since 2015-02-28 16:42
 */
@Component
public class CategoryListDirectiveModel implements TemplateDirectiveModel {
    private CategoryService categoryService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        List<Category> categoryList = categoryService.listAll();
        env.setVariable("categoryList", ObjectWrapper.DEFAULT_WRAPPER.wrap(categoryList));
        body.render(env.getOut());
    }

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}
